package com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10;

import com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton;

import java.lang.reflect.Constructor;

/**
 * @PROJECT_NAME design_patterns
 * @DESCRIPTION 测试类
 * @AUTHOR CNBruceLee
 * @DATE 2021/7/8 20:15
 */
public class Test {

    //通过反射破话单例模式（改进前）
    @org.junit.Test
    public void test1() throws Exception {
        //1、实例化对象
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton singleton1 = Singleton.getInstance();

        Class<com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton> singletonClass = com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton.class;
        Constructor<com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton> constructor = singletonClass.getDeclaredConstructor();
        constructor.setAccessible(true);//取消访问检查
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton singleton2 = constructor.newInstance();//通过反射的形式创建Singleton对象
        Singleton singleton3 = constructor.newInstance();//通过反射的形式创建Singleton对象

        //通过放射获取的对象也痛了，而是两个，也破坏了单例模式
        System.out.println(singleton1 == singleton2);//-->false
        System.out.println(singleton2 == singleton3);//-->false
        System.out.println(singleton1);
        System.out.println(singleton2);
        System.out.println(singleton3);
    }

    //通过反射破话单例模式（改进后）
    @org.junit.Test
    public void test2() throws Exception {
        //1、实例化对象
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton singleton1 =
                com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton.getInstance();
        System.out.println(singleton1);

        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton singleton4 =
                com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton.getInstance();
        System.out.println(singleton4);

        Class<com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton> singletonClass =
                com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton.class;
        Constructor<com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton> constructor =
                singletonClass.getDeclaredConstructor();
        constructor.setAccessible(true);//取消访问检查
        //再次创建则报错，抛出异常
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo10.Singleton singleton2 = constructor.newInstance();//通过反射的形式创建Singleton对象
        System.out.println(singleton1 == singleton2);//-->true
        System.out.println(singleton2);


    }
}
